
package com.barrettsprivateers;

public class SwapUtil
{
    /** Convert a string into an equivalent string of hex digits.
     * this conversion works as long as the cdefault charset remains the same.
     */
    public static String stringToHex(String ipStr)
    {
        byte[] convert = ipStr.getBytes();
        
        String ret = "";
        for(int i = 0; i < ipStr.length(); i++ )
        {
            // high half
            ret = ret + nyb_to_ch((byte)(convert[i] >> 4));
            // low half
            ret = ret + nyb_to_ch((byte)(convert[i] & 0xF));
        }
        
        return ret;
    }
    
    private static char nyb_to_ch(byte b)
    {
        if(b < 0xA)
            return (char)('0'+b);
        
        return (char)('A'+(b-0xA));
    }
    
    /** Convert a string of hex digits into an equivalent string.
     * this conversion works as long as the cdefault charset remains the same.
     */
    public static String hexToString(String ipStr)
    {
        String ret;
        
        byte[] converted = new byte[ipStr.length()/2];
        
        for(int i = 0; i < ipStr.length(); i += 2)
        {
            converted[i/2] = ((byte)( 
                              (ch_to_nyb(ipStr.charAt(i)) << 4) + 
                              ch_to_nyb(ipStr.charAt(i+1)) 
                             ));
        }
        
        ret = new String(converted);
        
        return ret;
    }
    
    private static byte ch_to_nyb(char ch)
    {
        if(ch < 'A')
            return (byte)(ch - '0');
        
        return (byte)((ch - 'A')+ 0xA);
    }
    
    
    /**
     *  for testing methods
     */
    public static void main(String[] args)
    {
        /* Test the stringToHex and hexToString methods
         * needs more testing
        
        String test1 = "Twas brillig and the slithy toves,";
        String test2 = stringToHex(test1);
        String test3 = hexToString(test2);
        System.out.println(test1 + "\n" + test2 + "\n" + test3 + "\n" +
                            test3.equals(test1));
        /**/
    }
}
